package com.commerce.common.exception;

import com.commerce.common.utils.Result;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingClass;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 全局异常处理器
 * 仅在WebMvc环境下生效
 */
@Slf4j
@RestControllerAdvice
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@ConditionalOnMissingClass("org.springframework.web.reactive.config.WebFluxConfigurer")
public class GlobalExceptionHandler {

    /**
     * 处理HTTP消息不可读异常
     */
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public Result<String> handleHttpMessageNotReadableException(HttpMessageNotReadableException e, HttpServletRequest request) {
        log.error("请求URL: {}, 请求数据格式错误: {}", request.getRequestURL(), e.getMessage());
        return Result.error("请求数据格式错误，请确保发送正确的JSON格式数据");
    }

    /**
     * 处理所有未捕获的异常
     */
    @ExceptionHandler(Exception.class)
    public Result<String> handleException(Exception e, HttpServletRequest request) {
        log.error("请求URL: {}, 发生异常: ", request.getRequestURL(), e);
        return Result.error("系统异常，请稍后重试");
    }

    /**
     * 处理业务异常
     */
    @ExceptionHandler(BusinessException.class)
    public Result<String> handleBusinessException(BusinessException e, HttpServletRequest request) {
        log.error("请求URL: {}, 业务异常: {}", request.getRequestURL(), e.getMessage());
        return Result.error(e.getCode(), e.getMessage());
    }
} 